package de.lgohlke.helper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>ErrorHelper class.</p>
 *
 * @author lars
 * @version $Id: $
 */
public final class ErrorHelper
{
  private final static Logger log = LoggerFactory.getLogger(ErrorHelper.class);

  private ErrorHelper()
  {
    // ok
  }

  private static File dir = new File("errors");

  /**
   * <p>getFileWithSuffix.</p>
   *
   * @param timestamp a {@link java.lang.Long} object.
   * @param suffix a {@link java.lang.String} object.
   * @return a {@link java.io.File} object.
   */
  public static File getFileWithSuffix(final Long timestamp, final String suffix)
  {
    return new File(dir.getName() + "/" + timestamp + "." + suffix);
  }

  /**
   * <p>saveDataWithStacktrace.</p>
   *
   * @param e
   *          exception
   * @param data
   *          bytes
   * @return timestamp
   */
  public static synchronized long saveDataWithStacktrace(final Exception e, final byte[] data)
  {
    long timestamp = System.currentTimeMillis();
    try
    {
      initErrorDirectory();

      File errorlog = getFileWithSuffix(timestamp, "log");
      File dataLog = getFileWithSuffix(timestamp, "data.log");

      if (data != null)
      {
        FileUtils.writeByteArrayToFile(dataLog, data);
      }

      String errMsg = e.getMessage() + "\n\n";

      ByteArrayOutputStream os = new ByteArrayOutputStream();
      PrintStream ps = new PrintStream(os);
      e.printStackTrace(ps);
      ps.flush();
      os.flush();

      FileUtils.writeStringToFile(errorlog, errMsg + os.toString("UTF8"));

    }
    catch (IOException e1)
    {
      log.error(e1.getMessage(), e);
    }

    return timestamp;
  }

  /**
   * erstellt, wenn noch nicht vorhanden ein Verzeichnis für die logs
   */
  private static void initErrorDirectory()
  {
    if (dir.exists())
    {
      if (!dir.isDirectory())
      {
        dir = new File(dir.getName() + ".d");
        dir.mkdir();
      }
    }
    else
    {
      dir.mkdir();
    }
  }
}
